<?php
class Swoole_SwooleClient
{
    private $client;
    private $ip;
    private $port;

    public function __construct($ip,$port)
    {
        $this->client = new swoole_client(SWOOLE_SOCK_TCP);
        $this->connect($ip,$port);
    }

    public function connect($ip,$port)
    {
        if (!$this->client->connect($ip, $port, 1)) {
            throw new Exception(sprintf('Swoole Error: %s', $this->client->errCode. "IP:$ip,PORT:$port"));
        }
    }

    public function send($data)
    {
        if ($this->client->isConnected()) {
            if (!is_string($data)) {
                $data = json_encode($data);
            }
            //检验格式
            $opt = json_decode($data,1);
            if(!isset($opt['c']) && !isset($opt['a']) && !$opt['c'] && !$opt['a']){
                throw new Exception('Swoole Client params error.');
            }

            return $this->client->send($data);
        } else {
            throw new Exception('Swoole Server does not connected.');
        }
    }
    public function recv()
    {
        return $this->client->recv();
    }

    public function close()
    {
        $this->client->close();
    }
}



$opt = getopt("c:a:p:");
//控制器
if (!isset($opt['c']) ||  !isset($opt['a']) || !$opt['c'] || !$opt['a']) {
    $exitstr = <<<EOF
    执行命令格式:\033[31m
    (1) /usr/local/bin/php ./SwooleClient.php -c compensate -a _runSec -p 'id=123&bb=55'
\033[0m
EOF;
    exit($exitstr);
}
//读取配置
$arr_ini = parse_ini_file(__DIR__. '/app.ini');
$ip = $arr_ini['swoole.ip'];
$port = $arr_ini['swoole.port'];
if($ip && $port){
    $swooleClient = new Swoole_SwooleClient($ip,$port);
    //$swooleClient->connect();
    $send = $swooleClient->send($opt);
    //echo $swooleClient->recv();
    //$swooleClient->close();
}else{
    echo "\033[31m 获取IP或Port为空!\033[0m";
}

